package com.example.bbs.kafka.consumer;

import com.alibaba.fastjson.JSON;
import com.example.bbs.domain.entity.Post;
import com.example.bbs.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Slf4j
public class PostConsumer {

    @Autowired
    PostService postService;

    @KafkaListener(topics = "post-insert")
    public void processInsert(ConsumerRecord consumerRecord) {
        if (Objects.isNull(consumerRecord) || Objects.isNull(consumerRecord.value())) {
            return;
        }
        //解析数据
        Post post = JSON.parseObject((String) consumerRecord.value(), Post.class);
        //同步到数据库
        postService.save(post);
        log.info("帖子Id为[" + post.getPostId() + "]," + "主题为[post-insert]的消息消费成功!");
    }

    @KafkaListener(topics = "post-update")
    public void processUpdate(ConsumerRecord consumerRecord) {
        if (Objects.isNull(consumerRecord) || Objects.isNull(consumerRecord.value())) {
            return;
        }
        //解析数据
        Post post = JSON.parseObject((String) consumerRecord.value(), Post.class);
        //同步到数据库
        postService.update(post);
        log.info("帖子Id为[" + post.getPostId() + "]," + "主题为[post-update]的消息消费成功!");
    }
}
